﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

using Recon.Portal.Business;
using Recon.Portal.DataObjects;

namespace Recon.Portal.WebUI
{
    public partial class RoleMenuMapping : System.Web.UI.Page
    {
        public List<int> checkedValues;
        protected void 
            Page_Load(object sender, EventArgs e)
        {
            if (((User)Session["CurrentUserVO"]) == null)
            {
                Response.Redirect("ReconSignIn.aspx");
            }
            if (!IsPostBack)
            {
                btnSubmit.Visible = false;
                loadRoles();
            }
        }

        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            insertRoleMenuMapping();
        }

        private void loadRoles()
        {
            RoleEntity roleEntity = new RoleEntity();
            List<UserRole> roles = roleEntity.GetAllRoles(((User)Session["CurrentUserVO"]).UserType == "S", ((User)Session["CurrentUserVO"]).CustomerID);

            if (roles != null && roles.Count<UserRole>() > 0)
            {
                ddlRole.Items.Clear();
                ddlRole.Items.Add(new ListItem("Select Role", "0"));

                foreach (UserRole role in roles)
                {
                    ddlRole.Items.Add(new ListItem(role.RoleDescription, role.RoleID));
                }
            }
        }

        public void loadMenus(GridView control)
        {
            MenuManager menuMgr = new MenuManager();
            //get system menus only if system user
            List<Recon.Portal.DataObjects.MenuItem> menus = menuMgr.GetAllMenus(((User)Session["CurrentUserVO"]).UserType == "S");

            if (menus != null && menus.Count<Recon.Portal.DataObjects.MenuItem>() > 0)
            {
                control.DataSource = menus;
                control.DataBind();
            }
        }

        public void getRoleMenus()
        {
            try
            {
                MenuManager menuMgr = new MenuManager();
                List<Recon.Portal.DataObjects.MenuItem> menus = menuMgr.GetMenuForRole(ddlRole.SelectedValue);
                //Now mark checkbox as 'selected' if any menus are assigned to the selected role.
                {
                    if (menus != null && menus.Count<Recon.Portal.DataObjects.MenuItem>() > 0)
                    {
                        checkedValues = new List<int>();
                        //Get the menu id(s) which are assigned to role , into list.
                        for (int _intCounter = 0; _intCounter <= menus.Count<Recon.Portal.DataObjects.MenuItem>() - 1; _intCounter++)
                        {
                            int menuID = Convert.ToInt32(menus[_intCounter].MenuID);
                            checkedValues.Add(menuID);
                        }
                        Session["ExistingMenu"] = checkedValues.ToList<int>();
                        //Compare menus from list with the grid items and then mark checkbox as selected if matching
                        foreach (GridViewRow row in grvMenu.Rows)
                        {
                            HtmlInputCheckBox chk = (HtmlInputCheckBox)row.Cells[0].FindControl("chkIndividual");
                            int menuID = Convert.ToInt32(grvMenu.DataKeys[row.RowIndex].Value);
                            if ((checkedValues.Contains(menuID)))
                            {
                                chk.Checked = true;
                            }
                        }
                        //If All menus are selected then mark 'SelectAll' checkbox
                        if (checkedValues.Count == grvMenu.Rows.Count)
                        {
                            //CType(grvMenu.HeaderRow.FindControl("chkSelectAll"), HtmlInputCheckBox).Checked = True
                        }
                    }
                    btnSubmit.Visible = true;
                }
            }
            catch
            {
                btnSubmit.Visible = false;
            }
        }

        public void insertRoleMenuMapping()
        {
            RoleEntity roleEntity = new RoleEntity();
            //function used to insert map_rolemenu to the database
            string _strMenuIDS = "";
            Int32 _intCounter = 0;
            int retval = 0;
            foreach (GridViewRow row in grvMenu.Rows)
            {
                HtmlInputCheckBox chk = (HtmlInputCheckBox)row.Cells[0].FindControl("chkIndividual");
                int menuID = Convert.ToInt32(grvMenu.DataKeys[row.RowIndex].Value);
                if (chk.Checked)
                {
                    _intCounter = _intCounter + 1;
                    _strMenuIDS = _strMenuIDS + "," + menuID;
                }
            }
            if (_intCounter > 0)
            {
                _strMenuIDS = _strMenuIDS.Substring(1);
            }

            try
            {
                //Compare menus from list with the grid items and then mark checkbox as selected if matching
                if (Session["ExistingMenu"] != null)
                {
                    checkedValues = (List<int>)Session["ExistingMenu"];
                }
                foreach (GridViewRow row in grvMenu.Rows)
                {
                    HtmlInputCheckBox chk = (HtmlInputCheckBox)row.Cells[0].FindControl("chkIndividual");
                    int menuID = Convert.ToInt32(grvMenu.DataKeys[row.RowIndex].Value);
                    if (checkedValues != null)
                    {
                        if ((checkedValues.Contains(menuID)))
                        {
                            retval = roleEntity.removeRoleMenuMapping(ddlRole.SelectedValue.Trim(), Convert.ToString(menuID));
                            checkedValues.Remove(menuID);
                        }
                    }
                    if (chk.Checked)
                    {
                        retval = roleEntity.addRoleMenuMapping(ddlRole.SelectedValue.Trim(), Convert.ToString(menuID), 1, ((User)Session["CurrentUserVO"]).UserID,((User)Session["CurrentUserVO"]).CustomerID);
                        _intCounter = _intCounter + 1;
                    }
                }
                if (retval == 1)
                {
                    lblMessage.Text = "Role-Menu mapping done Successfully!";
                    btnClickPopup.Show();
                    ClearFields();
                    btnSubmit.Visible = false;
                }
                else if (retval == 2)
                {
                    lblMessage.Text = "Can not delete Role-Menu mapping for the selected Role!";
                    btnClickPopup.Show();
                    ClearFields();
                    btnSubmit.Visible = false;
                }
                else
                {
                    lblMessage.Text = "Error while mapping Role-Menu.";
                    btnClickPopup.Show();
                }
            }
            catch
            {
                lblMessage.Text = "Error while mapping role-menu";
                btnClickPopup.Show();
            }
            finally
            {
                _strMenuIDS = null;
                Session["ExistingMenu"] = null;
            }
        }

        private void ClearFields()
        {
            ddlRole.ClearSelection();
            ddlRole.SelectedValue = "0";
            grvMenu.DataSource = null;
            grvMenu.DataBind();
            Session["ExistingMenu"] = null;

        }

        protected void ddlRole_SelectedIndexChanged(object sender, EventArgs e)
        {
            // Get the list of all menus and bind to grid
            loadMenus(grvMenu);
            // Get the list of menus which are assigned to the selected role
            getRoleMenus();
        }

        protected void btnok_Click(object sender, EventArgs e)
        {
            btnClickPopup.Hide();
        }
    }
}